<template>
	<view class="pages">
		
		<!-- 头部 -->
		<!-- <page_head :back="1">推广分享</page_head> -->
		<pagehead>推广分享</pagehead>
		<view class="info">
			<view class="avatar" v-if="JSON.stringify(usermsg)!='{}'" v-show="usermsg.avatar"
					:style="{background:'url('+usermsg.avatar+') 100% /cover no-repeat'}">
				</view>
				<view class="avatar" v-else
					:style="{background:'url('+IMAGE_STATIC+'/images/logo.png) 100% /cover no-repeat'}">
				</view>
				<view class="name">
					{{usermsg.real_name?usermsg.real_name:'待实名'}}
				</view>
				<view class="txt">我的邀请码</view>
				<view class="code">
					{{usermsg.uid?usermsg.uid:''}}
				</view>
				<view class="copy" @click="$tools.copy(usermsg.uid)">复制</view>
		</view>
		<view class="qrocde">
			<image v-if="ewmImg != ''" :src="ewmImg" mode="" class="image"/>
		</view>
		<!-- <view class="share-box">
			<view class="share-title">点击右上角分享小程序或</view>
			<button type="size" class="share-btn noStyle" open-type="share" >复制邀请连接</button>
			<button type="size" class="share-btn noStyle" @tap.stop="showImg()">保存推广二维码</button>
			<!-- <view class="shareBtn" @click="share()">保存推广二维码</view> 
		</view>
		<view class="share">
			<view class="share-wrapper">
				<view class="share-header">
					<span class="tips"></span>
					<span class="head">推荐用户</span>
				</view>
				<view class="initNoData" v-if="inviteList.length == 0">暂无记录~</view>
				<view class="share-list" v-else>
					<scroll-view scroll-y="true" class="share-height" @scrolltolower="lower">
						<view class="share-item" v-for="(item,index) in inviteList" :key="index">
							<view class="share-left">
								<image v-if="item.avatar.substring(0,5) != 'https'" class="logo" :src="IMAGE_PREFIX +'/'+ item.avatar" mode=""></image>
								<image v-else class="logo" :src="item.avatar" mode=""></image>
								<view class="share-name">{{ item.nickName }}</view>
							</view>
							<view class="share-time">{{ item.createTime }}</view>
						</view>
					</scroll-view>
				</view>
			</view>
		</view>-->
		
		<view class="modal" v-if="inviteImgShow">
			<view class="modal-bg" @tap.stop="inviteImgShow = false">
				<!-- <image :src="hbUrl" mode="widthFix"></image> -->
				<view class="modal-box">
					<canvas :style="{ width: picWidth + 'px', height: picHight + 'px' }"
					canvas-id="myCanvas" id="myCanvas"></canvas>
				</view>
				
				<view class="btnBox">
					<view class="btnBox-btn" @tap.stop="saveHB()">
						保存图片
					</view>
				</view>
			</view>
		</view>
		
	</view>
</template>

<script>
	import QR from './qrcode/qrcode';
	import url from '@/common/js/url.js';
	export default {
		components:{ 
		},
		data(){
			return{
				IMAGE_STATIC: this.$url.assetsPath,
				IMAGE_PREFIX: this.$url.urlPath,
				inviteList: [],
				pageIndex: 1,
				pageSize: 10,
				usermsg: {},
				appkey: '',
				access_token: '',
				openlink: '',
				wxaqrcodeObj: {},
				size: 100,
				
				inviteImgShow: false,
				canvasW: 0, // 画布宽
				canvasH: 0, // 画布高
				picWidth: '', //图片宽
				picHight: '', //图片高
				SystemInfo: {}, // 设备信息
				goodsImg: {}, // 主图
				ewmImg: '', // 二维码图片
				ewmW: 160, // 二维码大小
				hbUrl: ''  ,// 保存的图片地址
				ewmImg2: '',
				shareUrl: '',
				shareImg: '',
			}
		},
		onLoad() {
			this.usermsg = uni.getStorageSync('usermsg');
			console.log("usermsg：",this.usermsg);
			// #ifdef MP-WEIXIN || MP
			// this.getAppKey();
			// #endif
			// uni.showShareMenu({
			// 	//小程序的原生菜单中显示分享按钮，才能够让发送给朋友与分享到朋友圈两个按钮可以点击
			// 	menus:["shareAppMessage","shareTimeline"] //不设置默认发送给朋友
			// })
		},
		onShareAppMessage(res) {
			if (res.from === 'button') {// 来自页面内分享按钮
			  console.log('button',res.target);
			}
			if (res.from === 'menu') {// 来自页面内分享按钮
			  console.log('menu',res.target);
			}
			return {
				title: '启航掌柜',
				// path: '/pages/index/index?inviteUserId='+ this.globalData.userId,  // 路径，传递参数到指定页面。
				path: '/pagesMain/index/index?inviteUserId='+ this.usermsg.uid,  // 路径，传递参数到指定页面。
				imageUrl: 'https://api.anyueqc.cn/pics/images/logo.png',     //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
			}
		},
		onShow() {
			this.init();
		},
		methods: {
			init(){
				this.shareUrl = this.IMAGE_STATIC +'/#/?invite='+ this.usermsg.uid+'&inviteName='+this.usermsg.nick_name ;
				console.log(this.shareUrl);
				this.ewmImg = this.creatQrcode(this.shareUrl);
				// this.createwxaqrcode();
				// this.pageIndex = 1;
				// this.inviteList = [];
				// this.getInviteList();
			},
			creatQrcode(url) {
				if (url == '') {
					return false;
				}
				let img = QR.createQrCodeImg(url);
				return img;
			},
			showImg(){
				this.inviteImgShow = true;
				this.getMyCanvas();
			},
			async getMyCanvas(){
				let that = this;
				// 获取设备信息，获取设备的宽高，画布做一样的高度
				that.SystemInfo = await that.getSystemInfo();
				console.log('that.SystemInfo', that.SystemInfo)
				that.canvasW = that.SystemInfo.windowWidth; // 画布宽度
				that.canvasH = that.SystemInfo.windowHeight - 150; //画布高度
				//获取背景图片的长与宽，按画布的比例进行缩放
				that.goodsImg = await that.getImageInfo('https://api.anyueqc.cn/pics/bg.png'); //获取照片信信息
				// console.log("that.goodsImg:",that.goodsImg);
				that.picWidth = that.canvasW - 30;
				that.picHight = that.picWidth * that.goodsImg.height / that.goodsImg.width;
				// 如果主图，二维码图片，设备信息都获取成功，开始绘制海报，这里需要用setTimeout延时绘制，否则可能会出现图片不显示。
				if (that.goodsImg.errMsg == 'getImageInfo:ok' 
					&& that.SystemInfo.errMsg == 'getSystemInfo:ok'
				) {
					console.log('ok---二维码生成中');
					uni.showLoading({
						title: "二维码生成中"
					})
					setTimeout(() => {
						var ctx = uni.createCanvasContext('myCanvas');
						// 填充背景色，白色
						// ctx.setFillStyle('#fff'); // 默认白色
						// ctx.fillRect(0, 0, that.canvasW, that.canvasH) // fillRect(x,y,宽度，高度)
						// 绘制商品主图，二维码
						// ctx.drawImage(that.goodsImg.path, 15, 15, that.picWidth, that.picHight)
						// ctx.drawImage(that.ewmImg, 110, that.canvasH / 3.8, that.ewmW, that.ewmW)
						ctx.drawImage(that.goodsImg.path, 0, 0, that.picWidth, that.picHight)
						//  #ifdef APP-NVUE || H5
							ctx.drawImage(that.ewmImg, 95, that.canvasH / 4.2, that.ewmW, that.ewmW)
						// #endif
						//  #ifdef MP-WEIXIN
							ctx.drawImage(that.ewmImg2, 95, that.canvasH / 4.2, that.ewmW, that.ewmW)
						// #endif
						ctx.draw(true, (ret) => { // draw方法 把以上内容画到 canvas 中。
							uni.hideLoading();
							console.log("ret：",ret);
							uni.canvasToTempFilePath({ // 保存canvas为图片
								canvasId: 'myCanvas',
								quality: 1,
								complete: (res) => {
									console.log("图片res：",res);
									that.hbUrl = res.tempFilePath;
									console.log("保存的图片：",res.tempFilePath);
								},
							})
						});
					}, 1000)
				} else {
					console.log('err')
				}
				uni.showShareMenu({
					withShareTicket: true,
					menus: ["shareAppMessage", "shareTimeline"]
				})
			},
			saveHB() {
				console.log('点击了图片');
				let that = this;
				uni.saveImageToPhotosAlbum({
					filePath: that.hbUrl,
					success: function(res2) {
						uni.showToast({
							title: '保存成功，请从相册选择再分享',
							icon: "none",
							duration: 5000
						})
					},
					fail: function(err) {
						// console.log(err.errMsg);
					}
				})
			},
			// 获取图片信息
			getImageInfo(image) {
				return new Promise((req, rej) => {
					uni.getImageInfo({
						src: image,
						success: (res) => {
							req(res)
						},
					});
				})
			},
			// 获取设备信息
			getSystemInfo() {
				return new Promise((req, rej) => {
					uni.getSystemInfo({
						success: function(res) {
							req(res)
						}
					});
				})
			},
			// 生成二维码
			createwxaqrcode(){
				let that = this;
				that.$Ajax('/userinfo/app/getUnlimitedQRCode',{
					// path: 'pages/index/index?inviteUserId='+ that.usermsg.userId, // 必须是已经发布的小程序存在的页面（否则报错）,that.code就是邀请码
					page: 'pagesMain/index/index', // 必须是已经发布的小程序存在的页面（否则报错）,that.code就是邀请码
					scene: that.usermsg.userId, 
					// scene: "inviteUserId=" + that.usermsg.userId, 
				},res => {
					that.ewmImg = "data:image/PNG;BASE64," + uni.arrayBufferToBase64(res.data); //以图片的形式展示
					// that.ewmImg = "data:image/png;base64," + res.data; //以图片的形式展示
					// console.log("ewmImg：",that.ewmImg);
					// const fs = uni.getFileSystemManager();
					//随机定义路径名称
					// var times = new Date().getTime();
					// var codeimg = wx.env.USER_DATA_PATH + '/' + times + '.png';
					//将base64图片写入
					// fs.writeFile({
					// 	filePath: codeimg,
					// 	data: that.ewmImg.slice(22),
					// 	encoding: 'base64',
					// 	success: (res) => {
					// 		console.log('codeimg',codeimg)
					// 		that.ewmImg2 = codeimg;
					// 	}
					// });
				},err =>{},'GET')
			},
			share(){
				let that = this;
				console.log('我是分享');  //打印出来的就是:data-item='item'里的'item'值
				let times = new Date().getTime();
				let url = 'https://api.anyueqc.cn/share/share.html?inviteUserId='+ this.usermsg.userId+'&times='+times;
				that.$tools.copy(url);
				console.log("openlink：",that.openlink);
				// let url = that.openlink;
				// that.$tools.copy(url);
				// location.href = 'weixin://dl/business/?inviteUserId='+ this.usermsg.userId
			},
			getApp(){
				let that = this;
				uni.request({
					url: 'https://api.weixin.qq.com/wxa/generatescheme?access_token='+that.access_token,
					method:'POST',
					data: {
						"jump_wxa":{
							"path": "pagesMain/index/index",   //  pages前面不能有斜杠
							"query": "?inviteUserId="+ this.usermsg.userId,
							// "envVersion": "develop",   // 正式版为"release"，体验版为"trial"，开发版为"develop"，
						},
						"is_expire":false,
						// "env_version": "develop"
					},
					success(res) {
						console.log('openlink', res)
						if(res.data.errmsg == 'ok'){
							that.openlink = res.data.openlink;
						}
					},
					fail(err) {
						console.log("data:",data,typeof(data));
						console.log('err', err);
					}
				})
			},
			getAccessToken(){
				let that = this;
				uni.request({
					url: 'https://api.weixin.qq.com/cgi-bin/token',
					method:'GET',
					data: {
						appid: that.$url.wxId,
						secret: that.appkey,
						grant_type: "client_credential",
					},
					success(res) {
						console.log('access_token', res)
						that.access_token = res.data.access_token;
						that.getApp();
						// that.createwxaqrcode();
					},
					fail(err) {
						console.log('err', err);
					}
				})
			},
			getAppKey(){
				let that = this;
				that.$Ajax('/userinfo/app/config',{},res => {
					if (res.code == 200) {
						that.appkey = res.data.appSecret;
						// that.getAccessToken();
					}
				},err =>{},'GET')
			},
			// 邀请用户列表
			getInviteList() {
				let that = this;
				that.$Ajax('/userinfo/inviteList', {
					pageIndex: that.pageIndex,
					pageSize: that.pageSize
				}, res => {
					if(res.code == 200){
						that.pages = res.data.pages;
						that.inviteList = that.inviteList.concat(res.data.list);
					}
				}, err => {}, 'GET')
			},
			lower(e) {
				console.log("ddd")
				if (this.pageIndex >= this.pages) {
					return this.$tools.toast('到底了');
				} else {
					this.pageIndex++;
					console.log("+++")
					this.getInviteList();
				}
			},
			/* 弹出框公用 */
			openPopup(e) {
				this.$refs[e].open();
			},
			hidePopup(e) {
				this.$refs[e].close();
			},
			changePopup(e) {
				this.typePopup = e.type;
				console.log('popup ' + e.type + ' 状态', e.show);
			},
		},
		onPullDownRefresh() {
			console.log('refresh');
			setTimeout(function () {
				uni.stopPullDownRefresh();
			}, 1000);
		}
	}
</script>

<style lang="scss" scoped>
	/deep/ .header_fixed{
		background: none !important;
	}
	/deep/ .header_fixed{
		background: none   !important;
	}
	.pages{
		width: 100%;
		height: 100vh;
		background: url($uni-static-dir+'/userimage/share-bg.png') 100% no-repeat;
		background-repeat: no-repeat;
		background-size: 100% 100%;
		// height: 620rpx;
		// position: absolute;
		// /*  #ifdef H5 || APP-PLUS  */
		// top: -80rpx;
		// /*  #endif   */
		// /*  #ifdef MP-WEIXIN  */
		// top: -76rpx;
		// /*  #endif   */
		.info{
			margin-top: 178rpx;
			text-align: center;
			.avatar{
				width: 108rpx;
				height: 108rpx;
				margin: auto;
				border-radius: 100%;
			}
			.name{
				margin-top: 16rpx;
				font-weight: 600;
				font-size: 28rpx;
				color: #333333;
				line-height: 33rpx;
			}
			.txt{
				margin-top: 16rpx;
				font-size: 24rpx;
				color: #333333;
				line-height: 28rpx;
			}
			.code{
				margin-top: 16rpx;
				font-family: Inter, Inter;
				font-weight: bold;
				font-size: 72rpx;
				color: #333333;
				line-height: 84rpx;
			}
			.copy{
				width: 150rpx;
				text-align: center;
				margin: auto;
				margin-top: 40rpx;
				height: 50rpx;
				line-height: 50rpx;
				border-radius: 20rpx;
				background: #AD2926;
				font-size: 30rpx;
				color: #FFFFFF;
				border-radius: 72rpx;
			}
		}
		.qrocde{
			width: 316rpx;
			height: 316rpx;
			margin: auto;
			margin-top: 80rpx;
			border-radius: 16rpx 16rpx 16rpx 16rpx;
			border: 2rpx solid #E6E6E6;
			.image{
				width: 316rpx;
				height: 316rpx;
			}
		}
	}
	
	.modal{
		&-bg{
			width: 100vw;
			height: 100vh;
			z-index: 999;
			position: fixed;
			top: 0;
			inset: 0px;
			background-color: rgba(0, 0, 0, 0.4);
			transition-duration: 0.3s;
		}
		&-box{
			position: fixed;
			top: 50%;
			left: 50%;
			transform: translate(-50%,-50%);
		}
		&-wrapper{
			// background: rgba(0,0,0,0.5);
			// width: 100vw;
			// height: 100vh;
			// position: relative;
			// z-index: 99;
		}
		.shareBox{
			&-wrapper{
				position: fixed;
				top: 45%;
				left: 50%;
				transform: translate(-50%,-50%);
				margin: auto;
				width: 90%;
				background: #AD2926 ;
				border-radius: 30rpx;
				z-index: 9999;
				padding: 20rpx 55rpx 57rpx 46rpx;
				.hand{
					position: absolute;
					top: 79rpx;right: 55rpx;
					width: 229rpx;
					height: 141rpx;
				}
				.topBox{
					@include flexLeftColumn;
					.logo{
						width: 193rpx;
						height: 100rpx;
					}
					.topTips{
						font-size: 24rpx;
						font-family: PingFang SC-Bold, PingFang SC;
						font-weight: bold;
						color: #232323;
					}
				}
				.contentBox{
					@include flexCenterColumn;
					margin: 48rpx 0 35rpx;
					.text{
						font-size: 30rpx;
						font-family: PingFang SC-Bold, PingFang SC;
						font-weight: bold;
						color: #000000;
						margin-bottom: 15rpx;
					}
					.tips{
						font-size: 28rpx;
						font-family: PingFang SC-Light, PingFang SC;
						font-weight: 300;
						color: #000000;
					}
				}
				.imgBox{
					@include flexCenterColumn;
					position: relative;
					margin: 35rpx 0 24rpx;
					.codeBox{
						width: 332rpx;
						height: 332rpx;
						background: #FFFFFF;
						border-radius: 10rpx;
						margin-bottom: 196rpx;
						position: relative;
						z-index: 2;
						image{
							width: 100%;
							height: 100%;
							border-radius: 10rpx;
						}
					}
					.firstImg{
						width: 585rpx;
						height: 430rpx;
						position: absolute;
						bottom: 0;
						z-index: 1;
					}
				}
				.tips_1{
					font-size: 32rpx;
					font-family: PingFang SC-Regular, PingFang SC;
					font-weight: 400;
					color: #232323;
					text-align: center;
				}
				.tips_2{
					font-size: 22rpx;
					font-family: PingFang SC-Medium, PingFang SC;
					font-weight: 500;
					color: #5D5656;
					text-align: center;
					margin-top: 15rpx;
				}
			}
		}
		.btnBox{
			position: fixed;
			bottom: 0;
			left: 0;right: 0;
			background: #FFFFFF;
			width: 100%;
			// border-radius: 20rpx 20rpx 0 0;
			&-btn{
				font-size: 30rpx;
				font-family: PingFang SC-Regular, PingFang SC;
				font-weight: 600;
				color: #232323;
				text-align: center;
				padding: 30rpx 0 80rpx;
			}
		}
	}
	
	.share{
		position: relative;
		z-index: 3;
		&-height{
			height: calc(100vh - 650rpx);
		}
		&-box{
			@include flexCenterColumn;
			position: relative;
			z-index: 3;
		}
		&-title{
			font-size: 36rpx;
			font-family: PingFang SC-Bold, PingFang SC;
			font-weight: bold;
			color: $globalColor-fontStyle;
			margin: 80rpx 0 0rpx;
		}
		&-btn{
			font-size: 36rpx;
			font-family: PingFang SC-Bold, PingFang SC;
			font-weight: bold;
			color: $globalColor-fontStyle;
			border: 1px solid $globalColor-fontStyle;
			padding: 12rpx 90rpx;
			border-radius: 10rpx 10rpx 10rpx 10rpx;
		}
		&-wrapper{
			margin: 100rpx 0 0;
			background: $globalColor-white;
			padding: 40rpx;
		}
		&-header{
			@include flexLeft;
			border-bottom: 1px solid $globalColor-border;
			padding-bottom: 34rpx;
			.tips{
				width: 4rpx;
				height: 32rpx;
				background: #AD2926;
				margin-right: 20rpx;
			}
			.head{
				font-size: 32rpx;
				font-family: PingFang SC-Bold, PingFang SC;
				font-weight: bold;
				color: #333333;
			}
		}
		&-list{
			
		}
		&-item{
			@include flexBetween;
			margin-top: 40rpx;
		}
		&-left{
			@include flexLeft;
			.logo{
				width: 52rpx;
				height: 52rpx;
				margin-right: 20rpx;
				border-radius: 50%;
			}
		}
		&-name{
			font-size: 30rpx;
			font-family: PingFang SC-Regular, PingFang SC;
			font-weight: 400;
			color: $globalColor-fontStyle;
		}
		&-time{
			font-size: 30rpx;
			font-family: PingFang SC-Regular, PingFang SC;
			font-weight: 400;
			color: #888B95;
		}
	}
	.noStyle{
		width: 396rpx !important;
		padding: 0 !important;
		margin: 30rpx 0 0 !important;
		background: none !important;
		height: 80rpx  !important;
		line-height: 80rpx !important;
	}
</style>